package com.fyzk.activity.popupwindow;

import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.view.Gravity;
import android.view.View;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.TextView;

import com.fyzk.activity.app.ActivityTaskManager;
import com.fyzk.activity.app.AppToast;
import com.fyzk.activity.chongzhi.RechargeActivity;
import com.fyzk.activity.lottery.recommend_order.MyRecommendOrderBean;
import com.fyzk.activity.user.LoginActivity;
import com.fyzk.data.AppLotteryInfos;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.net.Commands;
import com.fyzk.utils.AppUtil;
import com.fyzk.utils.SoftKeyboardUtils;
import com.fyzk.utils.SpanUtils;
import com.fyzk.utils.StringUtils;
import com.fyzk.utils.TimeUtil;
import com.fyzk.view.NumberPickerView;
import com.fyzk.view.ViewCallBack;
import com.tyjc.lottery.R;

import org.json.JSONException;
import org.json.JSONObject;

import http.Common.CommandUtil;
import http.StringResultBean;
import razerdp.basepopup.BasePopupWindow;

/**
 * 立即跟单弹窗
 */
public class FollowDocumentaryPopupWindow extends BaseRequestPopupWindow implements View.OnClickListener {

    //发单人，过关方式
    private TextView tv_sender_name, tv_pass_way;
    //自购金额，起跟金额，实付金额和佣金比例
    private TextView tv_buy_self, tv_start_money, tv_total_amount_brokerage;
    //人气火把
    private ImageView iv_hot1, iv_hot2, iv_hot3;
    //投注倍数
    private NumberPickerView mNumberPickView;
    //取消，确定
    private TextView tv_cancel, tv_confirm;

    private MyRecommendOrderBean mInfo;

    private AlertDialog payDialog;

    @Override
    public View onCreateContentView() {
        return createPopupById(R.layout.popup_follow_documentary);
    }

    @Override
    protected Animation onCreateShowAnimation() {
        return getTranslateVerticalAnimation(1f, 0, 400);
    }

    @Override
    protected Animation onCreateDismissAnimation() {
        return getTranslateVerticalAnimation(0, 1f, 400);
    }

    public FollowDocumentaryPopupWindow(Context context, MyRecommendOrderBean info) {
        super(context);

        setPopupGravity(Gravity.BOTTOM);
        setOutSideDismiss(false);
        setAdjustInputMethod(true);

        this.mInfo = info;

        initView();
        initData();
        initListener();

        setAutoShowInputMethod(mNumberPickView.getNumberEditText(), true);
    }

    private void initView() {
        tv_sender_name = findViewById(R.id.tv_sender_name);
        tv_pass_way = findViewById(R.id.tv_pass_way);
        tv_buy_self = findViewById(R.id.tv_buy_self);
        tv_start_money = findViewById(R.id.tv_start_money);
        tv_total_amount_brokerage = findViewById(R.id.tv_total_amount_brokerage);
        iv_hot1 = findViewById(R.id.iv_hot1);
        iv_hot2 = findViewById(R.id.iv_hot2);
        iv_hot3 = findViewById(R.id.iv_hot3);
        mNumberPickView = findViewById(R.id.mNumberPickView);
        tv_cancel = findViewById(R.id.tv_cancel);
        tv_confirm = findViewById(R.id.tv_confirm);
    }

    private void initData() {
        if (null == mInfo)
            return;
        setTopTitleText(tv_sender_name, "发单人：", mInfo.getUserName());
        setTopTitleText(tv_pass_way, "过关方式：", mInfo.getPlayName());
        setLotteryText(tv_buy_self, "自购", String.format("%s米", StringUtils.getDoubleString(mInfo.getAmount() / 100)));
        setLotteryText(tv_start_money, "起跟金额", String.format("%s米", StringUtils.getDoubleString(mInfo.getStartingAmount())));
        iv_hot1.setVisibility(mInfo.getFollowTotalNumber() >= 1 ? View.VISIBLE : View.GONE);
        iv_hot2.setVisibility(mInfo.getFollowTotalNumber() >= 4 ? View.VISIBLE : View.GONE);
        iv_hot3.setVisibility(mInfo.getFollowTotalNumber() >= 7 ? View.VISIBLE : View.GONE);

        mNumberPickView
//                .setMaxValue(99999) //最大输入值，也就是限量，默认无限大
                .setCurrentInventory(99999) // 当前的库存
                .setMinDefaultNum(1)  // 最小限定量
                .setCurrentNum(10)  // 当前数量
                .setmOnClickInputListener(new NumberPickerView.OnClickInputListener() {
                    @Override
                    public void onWarningForInventory(int inventory) {
                        AppToast.getToast().show("超过最大投注倍数");
                        setRealPriceAndBrokerageText(inventory);
                    }

                    @Override
                    public void onWarningMinInput(int minValue) {
                        AppToast.getToast().show("低于最小投注倍数");
                        setRealPriceAndBrokerageText(minValue);
                    }

                    @Override
                    public void onWarningMaxInput(int maxValue) {
                        AppToast.getToast().show("超过最大投注倍数");
                        setRealPriceAndBrokerageText(maxValue);
                    }
                })
                .setOnInputNumberListener(new NumberPickerView.OnInputNumberListener() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence charSequence, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable editable) {
                        String inputText = editable.toString().trim();
                        if (StringUtils.isNumber(inputText)) {
                            try {
                                setRealPriceAndBrokerageText(Integer.parseInt(inputText));
                            } catch (NumberFormatException e) {
                            }
                        }
                    }
                });
        setRealPriceAndBrokerageText(mNumberPickView.getNumText());
    }

    /**
     * 设置顶部发单人、过关方式
     *
     * @param textView 设置的textview
     * @param title    发单人、过关方式标题
     * @param content  发单人、过关方式
     */
    private void setTopTitleText(TextView textView, String title, String content) {
        SpanUtils.with(textView)
                .append(title)
                .setForegroundColor(getContext().getResources().getColor(R.color.color_999999))
                .setFontSize(12, true)
                .append(content)
                .setForegroundColor(getContext().getResources().getColor(R.color.black))
                .setFontSize(16, true)
                .create();
    }

    /**
     * 设置中间方案信息
     *
     * @param textView 设置的textview
     * @param title    方案标题
     * @param content  方案内容
     */
    private void setLotteryText(TextView textView, String title, String content) {
        SpanUtils.with(textView)
                .appendLine(title)
                .setForegroundColor(getContext().getResources().getColor(R.color.color_999999))
                .setFontSize(12, true)
                .append(content)
                .setForegroundColor(getContext().getResources().getColor(R.color.black))
                .setFontSize(16, true)
                .create();
    }

    /**
     * 设置实付金额和佣金比例
     *
     * @param multiple 投注倍数
     */
    private void setRealPriceAndBrokerageText(int multiple) {
        SpanUtils.with(tv_total_amount_brokerage)
                .appendLine(String.format("实付金额：%s米", null == mInfo ?
                        0 :
                        StringUtils.getDoubleString(mInfo.getStartingAmount() * multiple)))
                .setForegroundColor(getContext().getResources().getColor(R.color.black))
                .setFontSize(16, true)
                .append(String.format("佣金比例：%d%%", null == mInfo ? 0 : mInfo.getProportions()))
                .setForegroundColor(getContext().getResources().getColor(R.color.color_999999))
                .setFontSize(12, true)
                .create();
    }

    private void initListener() {
        tv_cancel.setOnClickListener(this);
        tv_confirm.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_cancel://取消
                if (null != mOnButtonClickListener)
                    mOnButtonClickListener.onCancelClick(FollowDocumentaryPopupWindow.this);
                dismiss();
                break;
            case R.id.tv_confirm://确定
                confirm();
                break;
        }
    }

    @Override
    public boolean onBeforeDismiss() {
        SoftKeyboardUtils.hintSoftKeyboard(getContext(), mNumberPickView.getNumberEditText());
        return super.onBeforeDismiss();
    }

    private void confirm() {
        if (!MySharedPreferences.getInstance().getLoginStatus()) {
            AppLotteryInfos.clear();
            ViewCallBack.getInstance().countDownObjs.clear();
            ActivityTaskManager.getInstance().closeAllActivity();
            Intent intent = new Intent(getContext(), LoginActivity.class);
            getContext().startActivity(intent);
            return;
        }

        if (null == mInfo || !(mInfo.getOrderResultStatus() == 5
                && System.currentTimeMillis() < TimeUtil.stringToLong(mInfo.getEndTime()))) {
            AppToast.getToast().show("已经截止");
            return;
        }

        double balance = 0;
        try {
            balance = Double.parseDouble(MySharedPreferences.getInstance().getBalance().toString());
        } catch (Exception e) {

        }
        if (balance >= getMoney()) {
            showPayDialog();
        } else {
            showLeftMoneyLowDialog(getMoney(), balance);
        }
    }

    /**
     * 显示是否支付对话框
     */
    public void showPayDialog() {
        if (payDialog == null) {
            payDialog = new AlertDialog.Builder(getContext()).setTitle("温馨提示")
                    .setPositiveButton("确定", (dialog, which) -> {
                        dialog.cancel();
                        followOrderBet();
                    }).setNegativeButton("取消", (dialog, which) -> dialog.cancel()).create();
        }
        payDialog.setMessage("确认跟单，立即支付");
        payDialog.show();
    }

    /**
     * 跟单投注
     */
    private void followOrderBet() {
        try {
            JSONObject params = new JSONObject();
            params.put("betcode", mInfo.getBetcode());
            params.put("lotteryType", mInfo.getLotteryType());
            params.put("phase", mInfo.getPhase());
            params.put("amount", getMoney() * 100);
            params.put("multiple", getMultiple());
            params.put("oneAmount", 2 * 100);
            params.put("prizeOptimize", "0");//prizeOptimize奖金诱惑（优化：1；普通：0）
            params.put("codeFilter", "0");//codeFilter旋转过滤（过滤：1；普通：0）
            params.put("userCouponId", "");//优惠劵Id，非优惠劵投注可以不写
            params.put("recommendId", mInfo.getRecommendId());
            params.put("recommendOrderId", mInfo.getOrderid());

            httpPostJson(CommandUtil.FOLLOWORDERBET, Commands.FOLLOWORDERBET, params, true);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        switch (requestCode) {
            case CommandUtil.FOLLOWORDERBET:
                new AlertDialog.Builder(getContext())
                        .setTitle("提示")
                        .setMessage("跟单成功")
                        .setNegativeButton("完成", (dialog, which) -> {
                            dialog.cancel();
                            if (null != mOnButtonClickListener)
                                mOnButtonClickListener.onConfirmClick(FollowDocumentaryPopupWindow.this);
                            dismiss();
                        })
                        .setCancelable(false)
                        .create()
                        .show();
                break;
        }
    }

    @Override
    protected void onFailure(int requestCode, String errorCode, String message) {
        super.onFailure(requestCode, errorCode, message);
    }

    /**
     * 获取跟单总彩金
     *
     * @return
     */
    private long getMoney() {
        return mInfo.getStartingAmount() * getMultiple();
    }

    /**
     * 获取跟单倍数
     *
     * @return
     */
    private int getMultiple() {
        return mNumberPickView.getNumText();
    }

    private AlertDialog leftMoneyLowDialog = null;

    /**
     * 显示彩金不足对话框
     *
     * @param money
     * @param leftMoney
     */
    public void showLeftMoneyLowDialog(double money, double leftMoney) {
        if (leftMoneyLowDialog == null) {
            leftMoneyLowDialog = new AlertDialog.Builder(getContext()).setTitle("提示")
                    .setPositiveButton("去充值", (dialog, which) -> {
                        dialog.cancel();
                        Intent intent = new Intent(getContext(), RechargeActivity
                                .class);
                        getContext().startActivity(intent);
                    }).setNegativeButton("返回", (dialog, which) -> dialog.cancel()).create();
        }
        leftMoneyLowDialog.setMessage("彩金不足,彩金" + leftMoney +
                "米，需支付" + money + "米，还差" + AppUtil.formatToYuanLXS(money - leftMoney) + "米");
        leftMoneyLowDialog.show();
    }

    private onButtonClickListener mOnButtonClickListener;

    public interface onButtonClickListener {
        void onConfirmClick(BasePopupWindow popupWindow);

        void onCancelClick(BasePopupWindow popupWindow);
    }

    public void setOnButtonClickListener(onButtonClickListener mOnButtonClickListener) {
        this.mOnButtonClickListener = mOnButtonClickListener;
    }
}
